package com.yu.core.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import net.sf.json.JSONArray;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.yu.interceptor.LogInterceptor;
import com.yu.model.Article;
import com.yu.model.Comment;
import com.yu.model.CommentZan;
import com.yu.model.Course;
import com.yu.model.Member;
import com.yu.model.MemberDetail;
import com.yu.model.Module;
import com.yu.model.Order;
import com.yu.model.Score;
import com.yu.model.SubComment;
import com.yu.model.Word;
import com.yu.util.BaiduTranslateUtil;
import com.yu.util.DateUtil;
import com.yu.util.HtmlUtil;
import com.yu.util.HttpUtils;
import com.yu.util.PicUtil;
import com.yu.util.StringUtil;
import com.yu.util.UuidUtil;

@Before(LogInterceptor.class)
public class AppController extends Controller {

	public static final String SUCCESS = "0";

	public static final String SUCCESS_MSG = "ok";

	public static final String E10001 = "该手机号码已注册过！";

	public static final String E10002 = "手机格式不正确！";

	public static final String E10003 = "验证码不正确或超时！";

	public static final String E10004 = "邮箱格式不正确！";

	public static final String E10005 = "手机不能为空";

	public static final String E10007 = "账号或者密码错误";
	
	public static final String E10008 = "当前用户会员已到期，请联系时代国际英语.";

	public static final String E20001 = "当前用户不存在";
	public static final String E20002 = "当前用户已过期";
	
	public static final String E20003 = "当前用户无权操作";

	public static final String E20004 = "没有权限操作";
	
	public static final String E20005 = "课程已下线或者不存在";
	public static final String E20006 = "您已点赞";
	
	public static final String E20007 = "请提前90分钟退课.";
	
	public static final String E20012 = "课程已经满员";
	
	public static final String E20014 = "课程已结束";
	
	public static final String E20011 = "课程已经开始，不能预订";
	
	public static final String E20021 = "课程已经开始，不能退订";
	
	public static final String E20008 = "还有未评价的课程，请先评价课程";
	
	public static final String E20009 = "游客没有权限，请联系时代国际英语";
	
	public static final String E20010 = "请先预习该课程";
	
	public static final String E20013 = "必须上完20次必修课程以后才能开始考试";
	
	public static final String E20024 = "你的vip等级 相同名称的必修课只能订一次";
	
	public static final String E20025 = "请完成 预定必修课的课后作业";
	
	public static final String E20026 = "你已评价过此课程";
	
	public static final String E20027 = "请先完成 课后作业";
	
	public static final String E50001 = "数据库异常！";

	public void version(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		result.put("version", PropKit.get("version"));
		result.put("url", PropKit.get("url"));
		renderText(JSONArray.fromObject(result).toString());
	}
	
	public void getToken(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
        try {
            result.put("errcode", SUCCESS);
            result.put("errmsg", SUCCESS_MSG);
            result.put("record" , PicUtil.getUptoken());
        } catch(Exception e){
            e.printStackTrace();
            result.put("errcode", "E50001");
            result.put("errmsg", E50001);
        }
        renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 用户注册
	 */
	public void register() {
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		try {
            Pattern mobilesPattern = Pattern.compile("[1]\\d{10}");
            if (!mobilesPattern.matcher(getPara("mobile")).matches()){
                result.put("errcode", "E10002");
                result.put("errmsg", E10002);
            } else {
            	// 判断手机号是否重复
    			int size = MemberDetail.dao.find("select * from sdw_member_detail where sdw_member_detail.mobile = '"+getPara("mobile")+"'").size() ;
    			if (size >0 ){
    				result.put("errcode", "E10001");
    				result.put("errmsg",  E10001);
    			} else {
    				Member member = new Member();
    				member.set("head", PicUtil.QINIU_DIR + getPara("head"));
    				member.set("regdate", new Date().getTime()/1000);
    				String encrypt = UuidUtil.get32Id().substring(1, 7);
    				member.set("encrypt", encrypt);
    				String url = "http://times2008.com/md5.php?md5str="+getPara("password")+"&encrypt="+encrypt ;
    				String md5Password = HttpUtils.sendGet(url);
    				member.set("password", md5Password);
    				member.set("username", getPara("mobile"));
    				member.set("nickname", getPara("nickname"));
    				member.set("lastdate", new Date().getTime()/1000);
    				member.set("start_time", new Date().getTime()/1000);
    				member.set("end_time", new Date().getTime()/1000 + 365*24*60*60);
    				member.set("email", getPara("email"));
    				member.set("groupid", 8);
    				member.set("point", 0);
    				member.set("chinese_realname", getPara("nickname"));
    				member.set("english_realname", getPara("nickname"));
    				member.set("book_type", 0);
    				member.save();
    				
    				MemberDetail memberDetail = new MemberDetail();
    				memberDetail.set("userid", member.getInt("userid"));
    				memberDetail.set("mobile", getPara("mobile"));
    				memberDetail.set("leave_total_days", 0);
    				memberDetail.set("number_56", 0);
    				memberDetail.set("number_87", 0);
    				memberDetail.set("total_56", 0);
    				memberDetail.set("total_87", 0);
    				memberDetail.save();
    				result.put("errcode", SUCCESS);
    				result.put("errmsg", SUCCESS_MSG);
    			}
            }
			
		} catch (Exception e) {
			e.printStackTrace();
			result.put("errcode", "E50001");
			result.put("errmsg", E50001);
		}
		renderText(JSONArray.fromObject(result).toString());
    }
	
	/*
	 * 用户登陆
	 */
	public void login() {
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		
		Member member = Member.dao.findFirst("select * from sdw_member as a left JOIN sdw_member_detail as b on a.userid = b.userid where a.username ='"+getPara("mobile")+"' or b.mobile ='"+getPara("mobile")+"'");
		if (member !=null){
			String url = "http://times2008.com/md5.php?md5str="+getPara("password")+"&encrypt="+member.getStr("encrypt");
			String md5Password = HttpUtils.sendGet(url);
			if(member.getStr("password").equals(md5Password)){
				
				if (member.getInt("end_time")!=null && (long)member.getInt("end_time") * 1000 > System.currentTimeMillis()){
					result.put("userid", member.get("userid"));
					result.put("head", member.getStr("head"));
					result.put("nickname", member.getStr("nickname"));
					
					Member member2 = Member.dao.findFirst("select a.userid, c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+member.get("userid"));
					result.put("level", member2.getStr("groupName"));
					result.put("errcode", SUCCESS);
					result.put("errmsg", SUCCESS_MSG);
				} else {
					result.put("errcode", "E10008");
					result.put("errmsg", E10008);
				}
				
			} else {
				result.put("errcode", "E10007");
				result.put("errmsg", E10007);
			}
		} else {
			result.put("errcode", "E10007");
			result.put("errmsg", E10007);
		}		
		renderText(JSONArray.fromObject(result).toString());
    }

	/*
	 * 检查手机是否重复
	 */
	public void mobileForUser() {
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		
		Pattern mobilesPattern = Pattern.compile("[1]\\d{10}");
        if (!mobilesPattern.matcher(getPara("mobile")).matches()){
            result.put("errcode", "E10002");
            result.put("errmsg", E10002);
        } else {
        	MemberDetail memberDetail = MemberDetail.dao.findFirst("select * from sdw_member_detail where sdw_member_detail.mobile = '"+getPara("mobile")+"'");
        	if (memberDetail !=null){
        		result.put("errcode", "E10001");
				result.put("errmsg",  E10001);
        	} else {
        		result.put("errcode", SUCCESS);
        		result.put("errmsg", SUCCESS_MSG);
        	}
        }
		renderText(JSONArray.fromObject(result).toString());
    }
	
	/*
	 * 密码重置
	 */
	public void resetPassword() {
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Pattern mobilesPattern = Pattern.compile("[1]\\d{10}");
        if (!mobilesPattern.matcher(getPara("mobile")).matches()){
            result.put("errcode", "E10002");
            result.put("errmsg", E10002);
        } else {
        	MemberDetail memberDetail = MemberDetail.dao.findFirst("select * from sdw_member_detail where sdw_member_detail.mobile = '"+getPara("mobile")+"'");
        	if (memberDetail !=null){
        		int userid = memberDetail.getInt("userid");
        		Member member = Member.dao.findFirst("select * from sdw_member where userid ="+userid);
        		if (member!=null){
        			String url = "http://times2008.com/md5.php?md5str="+getPara("password")+"&encrypt="+member.getStr("encrypt");
        			String md5Password = HttpUtils.sendGet(url);
        			member.set("password", md5Password);
        			member.update();
        			result.put("errcode", SUCCESS);
            		result.put("errmsg", SUCCESS_MSG);
        		} else {
        			result.put("errcode", "E20001");
            		result.put("errmsg", E20001);
        		}
        	} else {
        		result.put("errcode", "E20005");
        		result.put("errmsg", E20005);
        	}
        }
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 获取本周课程
	 */
	public void weekcourses(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		String catid = "56";
		if (getPara("catid")!= null){
			catid = getPara("catid");
		} 
		Calendar cal = Calendar.getInstance();
    	cal.add(Calendar.DATE, 1- cal.get(Calendar.DAY_OF_WEEK)+1);
    	cal.set(Calendar.HOUR_OF_DAY, 0);
    	cal.set(Calendar.MINUTE, 0);
    	cal.set(Calendar.SECOND, 0);
    	String start= DateUtil.commonDateTimeFormat.format(cal.getTime());
    	cal.add(Calendar.DATE, 7);
    	String end = DateUtil.commonDateTimeFormat.format(cal.getTime());
    	System.out.println("start :"+ start+" end :"+ end);
    	List<Course> courses = Course.dao.find("select id,title,starttime ,endtime,teacher,classroom,level,amountd,amount  from sdw_product  where catid ="+catid+" and starttime >'"+start+"'  and  endtime < '"+ end +"'");
    	result = new LinkedHashMap<String,Object>();
    	List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
    	String level = null;
    	if (getPara("userid")!=null){
    		Member member = Member.dao.findFirst("select a.userid, c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
    		level = member.getStr("groupName");
    	}
    	
    	for (Course  course: courses) {
    		Map<String,Object> c = new LinkedHashMap<String,Object>();
    		c.put("id", course.getInt("id"));
    		c.put("classroom", course.getStr("classroom"));
    		c.put("title", course.getStr("title")+ (course.getLong("amountd").intValue()== course.getLong("amount").intValue()?"(F)":""));
    		try {
				Date startTime = new Date(course.getTimestamp("starttime").getTime());
				Date endtime = new Date(course.getTimestamp("endtime").getTime());
				c.put("time", DateUtil.commonShortDateFormatForChinese.format(startTime) +" " + DateUtil.getWeekOfDate(startTime));
				c.put("start", DateUtil.commonShortTimeFormat.format(startTime));
				c.put("end", DateUtil.commonShortTimeFormat.format(endtime));
				c.put("teacher", course.getStr("teacher"));
				c.put("classroom", course.getStr("classroom"));
				String[] levels = course.getStr("level").split(",");
				if (getPara("userid")==null || (level!=null && Arrays.asList(levels).contains(level))){
					System.out.println(course.getLong("amountd").intValue());
		    		System.out.println(course.getLong("amount").intValue());
					record.add(c);
				}
				
			} catch (Exception e) {

			}
		}
    	result.put("record", record);
    	result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
    	renderText(JSONArray.fromObject(result).toString());
	}
	
	
	/*
	 * 获取课程详细
	 */
	public void course(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Member member = Member.dao.findFirst("select a.userid, c.`name` as groupName,a.point, FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87 from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		if(member!=null){
			result.put("userid", member.getInt("userid"));
			result.put("level", member.getStr("groupName"));
			result.put("point", member.get("point"));
			Course course = Course.dao.findFirst("select id,title,starttime ,endtime,teacher,classroom,amount,amountd,description  from sdw_product where id='"+getPara("id")+"'");
			
			Order order1 = Order.dao.findFirst("select * from sdw_destine where userid="+getPara("userid") +" and catidid="+getPara("id"));
			if(order1==null){
				result.put("action", "订课");
			} else {
				result.put("action", "退课");
			}
			result.put("title", course.getStr("title"));
			//result.put("level", course.getStr("level"));
			result.put("starttime", DateUtil.commonDateTimeFormat.format(new Date(course.getTimestamp("starttime").getTime())));
			result.put("endtime",  DateUtil.commonDateTimeFormat.format(new Date(course.getTimestamp("endtime").getTime())));
			result.put("teacher", course.getStr("teacher"));
			result.put("classroom", course.getStr("classroom"));
			result.put("amount", course.getLong("amount"));
			result.put("amountd", course.getLong("amountd"));
			result.put("note", course.getStr("description"));
			
			List<Order> orders = Order.dao.find("select a.* ,b.chinese_realname,b.english_realname,c.mobile from sdw_destine as a LEFT JOIN sdw_member as b on a.userid = b.userid LEFT JOIN sdw_member_detail as c on a.userid = c.userid where a.catidid ='"+course.getInt("id")+"'");
			List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
			for(Order order: orders){
				Map<String,Object> c = new LinkedHashMap<String,Object>();
				c.put("userid", order.getStr("userid"));
				c.put("username", order.getStr("username"));
				c.put("nickname", order.getStr("nickname"));
				c.put("chinesename", order.getStr("chinese_realname"));
				c.put("englishname", order.getStr("english_realname"));
				c.put("mobile", order.getStr("mobile"));
				record.add(c);
			}
			result.put("record", record);
			result.put("errcode", SUCCESS);
			result.put("errmsg", SUCCESS_MSG);
		} else {
			result.put("errcode", "E20001");
			result.put("errmsg", E20001);
		}
    	renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 我的课程
	 */
	public void myCourses(){
		Map<String,Object> result = new LinkedHashMap<String,Object>(); 
		Member member = Member.dao.findFirst("select a.userid, c.`name` as 'level',FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87,a.head,a.nickname,a.username,a.point from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		result.put("userid", member.getInt("userid"));
		result.put("level", member.getStr("level"));
		result.put("head", member.getStr("head"));
		result.put("name", member.getStr("nickname"));
		result.put("number", member.get("username"));
		result.put("point", member.get("point"));
		result.put("number56", member.getLong ("number_56"));
		result.put("number87", member.getLong("number_87"));
		//必修课可预订总次数
		result.put("total56", member.getLong ("total_56"));
		result.put("total87", member.getLong("total_87"));
		if (member.getTimestamp("starttime")!=null){
			result.put("starttime", DateUtil.commonDateTimeFormat.format(new Date(member.getTimestamp("starttime").getTime())));
		} else {
			result.put("starttime", "-");
		}
		if (member.getTimestamp("endtime")!=null){
			result.put("endtime",  DateUtil.commonDateTimeFormat.format(new Date(member.getTimestamp("endtime").getTime())));
			result.put("spareDay", -1*DateUtil.daysBetween(new Date(member.getTimestamp("endtime").getTime())));
		} else {
			result.put("endtime", "-");
			result.put("spareDay", "-");
		}

		
		int currentPage = 1;
        int maxCount = 20;
        // 必须课程
        int catid = 56;
        try{
            currentPage = getParaToInt("currentPageStr");
            maxCount = getParaToInt("maxCountStr");
        } catch (Exception e){
        }
        try{
        	catid = getParaToInt("catid");
        } catch (Exception e){
        }
        int offset = (currentPage -1) * maxCount;
		List<Course> courses = Course.dao.find("SELECT a.username,a.nickname,a.title as title , b.starttime ,b.endtime,b.classroom,b.teacher, b.id  from  sdw_destine as a LEFT JOIN sdw_product as b on a.catidid = b.id where a.userid='"+getPara("userid")+"'  and  b.catid ='"+catid+"'  order by  a.inputtime desc   limit "+offset+" , "+maxCount);
    	List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
    	for (Course  course: courses) {
    		Map<String,Object> c = new LinkedHashMap<String,Object>();
    		c.put("id", course.get("id"));
    		c.put("title", course.getStr("title"));
    		try {
				Date startTime = new Date(course.getTimestamp("starttime").getTime());
				Date endtime = new Date(course.getTimestamp("endtime").getTime());
				c.put("time", DateUtil.commonShortDateFormatForChinese.format(startTime) +" " + DateUtil.getWeekOfDate(startTime));
				c.put("start", DateUtil.commonShortTimeFormat.format(startTime));
				c.put("end", DateUtil.commonShortTimeFormat.format(endtime));
				c.put("starttime", startTime.getTime());
				c.put("endtime", endtime.getTime());
				c.put("teacher", course.getStr("teacher"));
				c.put("classroom", course.getStr("classroom"));
				record.add(c);
			} catch (Exception e) {

			}
		}
    	result.put("record", record);
    	result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
    	renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 订课课程
	 */
	public void orderCourse(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Member member = Member.dao.findFirst("select a.userid,a.nickname,a.username, c.`name` as 'level',FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87 from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		if(member == null){
			result.put("errcode", "E20001");
			result.put("errmsg", E20001);
		} else if (DateUtil.daysBetween(new Date(member.getTimestamp("endtime").getTime())) >0) {
			result.put("errcode", "E20002");
			result.put("errmsg", E20002);
		} else {
			Course course = Course.dao.findFirst("select id,catid, title,starttime,endtime,level,teacher,classroom,amount,amountd,description,prepareid,preparename  from sdw_product where id='"+getPara("id")+"'");
			if (course!=null){
				int amount = 0;
				int amountd = 0;
				try{
					amount = Integer.parseInt(String.valueOf(course.getLong("amount")));
				}catch(Exception e){
					
				}
				try{
					amountd = Integer.parseInt(String.valueOf(course.getLong("amountd")));
				}catch(Exception e){
					
				}
				Order order = Order.dao.findFirst("select * from sdw_destine where userid="+getPara("userid") +" and catidid="+getPara("id"));
				Long starttime = course.getTimestamp("starttime").getTime();
				if(System.currentTimeMillis() > starttime && order == null){
					result.put("errcode", "E20011");
					result.put("errmsg", E20011);
				} else if (System.currentTimeMillis() > starttime && order != null){
					result.put("errcode", "E20021");
					result.put("errmsg", E20021);
				} else if (amount > 0 &&  amountd>= amount && order == null){
					result.put("errcode", "E20012");
					result.put("errmsg", E20012);
				} else {
					MemberDetail memberDetail = MemberDetail.dao.findById(getPara("userid"));
					String[] levels = course.getStr("level").split(",");
					int prepareid = course.get("prepareid") == null? 0 : course.getInt("prepareid");
					// 判断课程 对于用户是否有相应的权限
					//if (Arrays.binarySearch(levels, member.getStr("level"))>-1){
					if (Arrays.asList(levels).contains(member.getStr("level"))){
						boolean checkflg = false;
						if (prepareid >0){
							int total = 0;
							List<Article> prepareList = Article.dao.find("select id from app_article where type=16 and parentid  = "+prepareid);
							if (prepareList!=null){
								total = prepareList.size();
							}	
							if(total>0){
								List<Score> prepareOrderList = Score.dao.find("select * from app_score where  userid ="+getPara("userid") +" and  artid in (select id from app_article where parentid  = "+prepareid+") and score > 89");
								if (prepareOrderList!=null){
									checkflg = (prepareOrderList.size() >= total);
								}
							}
						} else {
							checkflg = true;
						}
						// 是否有未完成评论的课程
						List<Order> commentHistory1  = Order.dao.find("select * from sdw_destine where catid =56 and score is null and userid="+getPara("userid") +" and catidid!="+getPara("id"));
						// 选修课不需要 
						if(commentHistory1 ==null || commentHistory1.size() ==0 || course.getInt("catid") == 87){
							if (course.getInt("catid")!= 56 || checkflg){
								// 是否有为完成的评论
								List<Order> commentHistory  = Order.dao.find("select * from sdw_destine where catid =56 and score is null and userid="+getPara("userid") +" and catidid!="+getPara("id"));
								if(commentHistory ==null || commentHistory.size() ==0 || course.getInt("catid") == 87){
									// 是否有为完成的作业
									int total = 0;
									boolean taskflg = course.getInt("catid") == 87;
									if (!taskflg){
										List<Article> taskList = Article.dao.find("select id from app_article where type=16 and parentid  = "+prepareid);
										if (taskList!=null){
											total = taskList.size();
										}	
										List<Score> taskOrderList = Score.dao.find("select * from app_score where  userid ="+getPara("userid") +" and  artid in (select id from app_article where parentid  = "+prepareid+") and score1 > 89");
										if (taskOrderList!=null){
											taskflg = (taskOrderList.size() >= total);
										}
									}
									if (taskflg){
										if (order == null){
											// 同名称的必修课只能订一次
											boolean sameflg = false;
											if ("level0".equals(member.getStr("level")) || "level1".equals(member.getStr("level"))){
												sameflg = true;
											} else {
												List<Order> sameHistory = Order.dao.find("select * from sdw_destine where catid =56  and userid="+getPara("userid") +" and title='"+course.get("title")+"'");
												sameflg = (sameHistory== null || sameHistory.size() ==0);
											}
											
											if (sameflg){
												order = new Order();
												order.set("desid", 0);
												order.set("catid", course.getInt("catid"));
												order.set("catidid", course.getInt("id"));
												order.set("title", course.getStr("title"));
												order.set("userid", member.getInt("userid"));
												order.set("username", member.getStr("username"));
												order.set("nickname", member.getStr("nickname"));
												order.set("grade", member.getStr("level"));
												order.set("inputtime", new Date().getTime()/1000);
												order.save();
												if (course.getInt("catid")== 56){
													memberDetail.set("number_56", memberDetail.getLong("number_56")+1L);
												} else {
													memberDetail.set("number_87", memberDetail.getLong("number_87")+1L);
												}
												memberDetail.update();
												course.set("amountd", course.getLong("amountd")+1L);
												course.update();
												result.put("errcode", SUCCESS);
												result.put("errmsg", SUCCESS_MSG);
											} else {
												result.put("errcode", "E20024");
												result.put("errmsg", E20024);
											} // end sameflg
											
										} else {
											long min = (new Date(course.getTimestamp("starttime").getTime()).getTime() -new Date().getTime())/ (60*60*1000);
											if (min<=0L){
												result.put("errcode", "E20011");
												result.put("errmsg", E20011);
											} else if (min<90L){
												result.put("errcode", "E20007");
												result.put("errmsg", E20007);
											} else {
												order.delete();
												if (course.getInt("catid")== 56){
													memberDetail.set("number_56", memberDetail.getLong("number_56")-1L);
												} else {
													memberDetail.set("number_87", memberDetail.getLong("number_87")-1L);
												}
												memberDetail.update();
												course.set("amountd", course.getLong("amountd")-1L);
												course.update();
												result.put("errcode", SUCCESS);
												result.put("errmsg", SUCCESS_MSG);
											}
										} // end order == null
									} else {
										result.put("errcode", "E20025");
										result.put("errmsg", E20025);
									}// end taskflg
								} else{
									result.put("errcode", "E20008");
									result.put("errmsg", E20008);
								} // end commentHistory ==null
							} else{
								result.put("id", prepareid);
								result.put("type", 13);
								result.put("name", course.get("preparename"));
								result.put("errcode", "E20010");
								result.put("errmsg", E20010 + course.get("preparename"));
							}
						} else {
							result.put("errcode", "E20008");
							result.put("errmsg", E20008);
						}
					} else {
						result.put("errcode", "E20003");
						result.put("errmsg", E20003);
					}
				}
			} else {
				result.put("errcode", "E20003");
				result.put("errmsg", E20003);
			}
		}
    	renderText(JSONArray.fromObject(result).toString());
	}
	
	
	
	/*
	 * 加入 生词本
	 */
	public void newWord(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Member member = Member.dao.findFirst("select a.userid,a.nickname,a.username, c.`name` as 'level',FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87 from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		if(member == null){
			result.put("errcode", "E20001");
			result.put("errmsg", E20001);
		} else {
			Word  word = new Word();
			word.set("userid", member.getInt("userid"));
			word.set("word", getPara("word"));
			try {
				word.set("transword", BaiduTranslateUtil.translate(getPara("word"), "en", "zh")  );
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			word.set("state", 0);
			word.set("inputtime", new Date().getTime()/1000);
			word.save();
			result.put("errcode", SUCCESS);
			result.put("errmsg", SUCCESS_MSG);
		}
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 生词本
	 */
	public void words(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Member member = Member.dao.findFirst("select a.userid,a.nickname,a.username, c.`name` as 'level',FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87 from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		if(member == null){
			result.put("errcode", "E20001");
			result.put("errmsg", E20001);
		} else {
			int currentPage = 1;
	        int maxCount = 20;
	        try{
	            currentPage = getParaToInt("currentPageStr");
	            maxCount = getParaToInt("maxCountStr");
	        } catch (Exception e){
	        }
	        int offset = (currentPage -1) * maxCount;
	        List<Word> words = Word.dao.find("select * from app_word where state=0  and userid =" +member.getInt("userid")+ " order by inputtime desc  limit "+offset+" , "+maxCount ) ;
	        
	        List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
	        for(Word word:words){
	        	Map<String,Object> c = new LinkedHashMap<String,Object>();
	        	c.put("id", word.getInt("id"));
	        	c.put("word", word.getStr("word"));
	        	c.put("transword", word.getStr("transword"));
	        	record.add(c);
	        }
	        result.put("record", record);
			result.put("errcode", SUCCESS);
			result.put("errmsg", SUCCESS_MSG);
		}
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 删除生词本
	 */
	public void delWord(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Member member = Member.dao.findFirst("select a.userid,a.nickname,a.username, c.`name` as 'level',FROM_UNIXTIME(a.start_time) as starttime, FROM_UNIXTIME(a.end_time) as endtime, b.number_56,b.number_87,b.total_56,b.total_87 from  sdw_member as a LEFT JOIN sdw_member_detail as b on a.userid = b.userid  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
		if(member == null){
			result.put("errcode", "E20001");
			result.put("errmsg", E20001);
		} else {
	        Word word = Word.dao.findById(getPara("id"));
	        if(word!=null){
	        	word.set("state", 1);
	        	word.update();
	        }
			result.put("errcode", SUCCESS);
			result.put("errmsg", SUCCESS_MSG);
		}
		renderText(JSONArray.fromObject(result).toString());
	}
	
	
	public void articles(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		int type = 3;
		try{
			type = getParaToInt("type");
		} catch (Exception e) {
		}
		int currentPage = 1;
        int maxCount = 20;
        try{
            currentPage = getParaToInt("currentPageStr");
            maxCount = getParaToInt("maxCountStr");
        } catch (Exception e){
        }
        int offset = (currentPage -1) * maxCount;
        List<Article> articles = null ;
        String userid = "0";
        if (!StringUtil.isEmpty(getPara("userid"))){
        	userid = getPara("userid");
        }
        Member member = Member.dao.findFirst("select c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid = "+userid);
        String group = null;
        if (member != null) {
        	group = " and `group` = '"+member.getStr("groupName")+"'";
        }
         
        if (StringUtil.isEmpty(getPara("parentid"))){
        	
        	// type 11 提交作业
        	if (type ==11 || type ==13 || type ==15 || type ==16 ){
        		// 升级考试
        		if(type ==15){
        			Order orderCnt = Order.dao.findFirst("select count(desid) as catid from sdw_destine where userid ="+userid);
        			int cnt = 0;
        			try{
        				cnt = Integer.parseInt(String.valueOf(orderCnt.get("catid")) );
        			}catch (Exception e) {
					}
        			/* TODO 20节课的逻辑 */
        			if(orderCnt !=null && cnt <20){
        				result.put("record", new ArrayList());
            			result.put("errcode", "E20013");
            			result.put("errmsg", E20013);
            			renderText(JSONArray.fromObject(result).toString());
            			return ;
        			}
        		}
        		if (group == null){
        			result.put("record", new ArrayList());
        			result.put("errcode", SUCCESS);
        			result.put("errmsg", SUCCESS_MSG);
        			renderText(JSONArray.fromObject(result).toString());
        			return ;
        		}
        		if(type==11 ){
        			Order nowOrder = Order.dao.findFirst("select * from sdw_destine where catid=56 and userid="+userid +" and score is null order by desid limit 1");
        			if (nowOrder==null){
        				result.put("record", new ArrayList());
            			result.put("errcode", SUCCESS);
            			result.put("errmsg", SUCCESS_MSG);
            			renderText(JSONArray.fromObject(result).toString());
            			return ;
        			} else{
        				System.out.println(nowOrder.get("catidid"));
        				Course newCourse = Course.dao.findById(nowOrder.get("catidid"));
        				if(newCourse==null){
        					result.put("record", new ArrayList());
                			result.put("errcode", SUCCESS);
                			result.put("errmsg", SUCCESS_MSG);
                			renderText(JSONArray.fromObject(result).toString());
                			return ;
        				} else
        					//newCourse.get("prepareid")
        					articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type = 16 and parentid = " +newCourse.get("prepareid"));
        			}
        		} else if( type==15){
        			// 获取当前订课的数据 
        			articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type = 16 and  id in (select DISTINCT artid from app_score where userid = "+userid+")"+ group +" order by inputtime desc  limit "+offset+" , "+maxCount ) ;
        			
        		} else{
        			articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type =" +type+ group +" order by inputtime desc  limit "+offset+" , "+maxCount ) ;
        		}
        		
        	} else {
        		articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type =" +type +" order by inputtime desc  limit "+offset+" , "+maxCount ) ;
        	}
        } else {
        	if (type ==11 || type ==13 || type ==15 || type ==16 ){
        		if (group == null){
        			result.put("record", new ArrayList());
        			result.put("errcode", SUCCESS);
        			result.put("errmsg", SUCCESS_MSG);
        			renderText(JSONArray.fromObject(result).toString());
        			return ;
        		}
        		if (type==15){
            		articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type =" +type+ "  and parentid="+getPara("parentid")+ group+ " order by inputtime desc ") ;
            	} else {
            		articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type =" +type+ "  and parentid="+getPara("parentid")+ group+ " order by inputtime desc  limit "+offset+" , "+maxCount ) ;
            	}
        	} else {
        		articles = Article.dao.find("select * , FROM_UNIXTIME(inputtime) as updatetime  from app_article where type =" +type+ "  and parentid="+getPara("parentid")+" order by inputtime desc  limit "+offset+" , "+maxCount ) ;
        	}
        	
        }
        List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
        for(Article article:articles){
        	Map<String,Object> c = new LinkedHashMap<String,Object>();
        	c.put("id", article.getInt("id"));
        	c.put("updatetime", DateUtil.meetDateTimeFormat.format(new Date(article.getTimestamp("updatetime").getTime())));
        	 
        	// 热门推荐
        	if (type==3){
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        		
        	// 每日一句
        	} else if (type==4) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("mp3", article.getStr("mp3url"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        		c.put("count",  Comment.dao.find("select * from app_comment  where artid="+article.getInt("id")).size());
        	// 分类学习
        	} else if (type==5) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        	// 挑战外教
        	} else if (type==6) {
        		c.put("logo", article.getStr("logo"));
        		c.put("icon", article.getStr("icon"));
        		c.put("title", article.getStr("title"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        		c.put("count",  Comment.dao.find("select * from app_comment  where artid="+article.getInt("id")).size());
        	// 视频练习
        	} else if (type==7) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("mp4", article.getStr("mp4url"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        	// 想唱就唱
        	} else if (type==8) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("mp3", article.getStr("mp3url"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        	// ECA活动
        	} else if (type==9) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        	// 新生必修课
        	} else if (type==10) {
        		c.put("logo", article.getStr("logo"));
        		c.put("title", article.getStr("title"));
        		c.put("content", article.getStr("content"));
        		c.put("content50", HtmlUtil.truncate2Chars(HtmlUtil.html2Text(article.getStr("content")), 50) );
        	// 提交作业
        	} else if (type==11){
        		c.put("content", article.getStr("content"));
        		c.put("content1", article.getStr("content1"));
        		String pattern = " |\\,|\\.|\\?|\\!|\\；|\\。|\\;";
     	        String[] arr =article.getStr("content").split(pattern);
     	        List list = Arrays.asList(arr);
     	        Collections.shuffle(list);
         	    c.put("part", JSONArray.fromObject(list).toString());
        		Score score = Score.dao.findFirst("select * from app_score where artid = "+article.getInt("id") +" and userid ="+getPara("userid") +" order by inputtime desc ");
        		if (score!=null){
        			c.put("score", score.getInt("score1"));
        		} else {
        			c.put("score", 0);
        		}
        	// 预约课文
        	}  else if (type==13){
        		c.put("content", article.getStr("content"));
        		c.put("title", article.getStr("title"));
        	// 预约考试
        	} else if (type==15){
        	   c.put("content", article.getStr("content"));
      	       String pattern = " |\\,|\\.|\\?|\\!|\\；|\\。|\\;";
    	       String[] arr =article.getStr("content").split(pattern);
    	       List list = Arrays.asList(arr);
    	       Collections.shuffle(list);
        	   c.put("part", JSONArray.fromObject(list).toString());
        		c.put("content1", article.getStr("content1"));
        		Score score = Score.dao.findFirst("select * from app_score where artid = "+article.getInt("id") +" and userid ="+getPara("userid") +" order by inputtime desc ");
        		if (score!=null){
        			c.put("score", score.getInt("score2"));
        		} else {
        			c.put("score", 0);
        		}
        	//  课文 题目
        	} else if (type==16){
        		c.put("content", article.getStr("content"));
        		c.put("content1", article.getStr("content1"));
        		Score score = Score.dao.findFirst("select * from app_score where artid = "+article.getInt("id") +" and userid ="+getPara("userid") +" order by inputtime desc ");
        		if (score!=null){
        			c.put("score", score.getInt("score"));
        		} else {
        			c.put("score", 0);
        		}
        	}
        	record.add(c);
        }
        result.put("record", record);
		result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 文章下的评论
	 */
	public void comments(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		
		int currentPage = 1;
        int maxCount = 20;
        try{
            currentPage = getParaToInt("currentPageStr");
            maxCount = getParaToInt("maxCountStr");
        } catch (Exception e){
        }
        int offset = (currentPage -1) * maxCount;
        List<Comment> comments = null;
        Article article = Article.dao.findById(getPara("id"));
        if(article.getInt("type")==6){
        	Comment comment = Comment.dao.findFirst("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " order by a.inputtime desc");
        	if (currentPage == 1){
        		// 最新一条
        		comments = new LinkedList<Comment>();
        		comments.add(comment);
        		if (comment!=null){
        			System.out.println("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " and  id !="+comment.getInt("id")+" order by a.zan desc  limit 0 , 19");
            		System.out.println(Comment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " and  id !="+comment.getInt("id")+" order by a.zan desc  limit 0 , 19"));
            		comments.addAll(Comment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " and  id !="+comment.getInt("id")+" order by a.zan desc  limit 0 , 19"));
        		}
        	} else {
        		comments = Comment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " and  id !="+comment.getInt("id")+ " order by a.zan  desc  limit "+offset+" , "+maxCount );
        	}
        } else {
        	comments = Comment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " order by a.inputtime desc  limit "+offset+" , "+maxCount );
        }
		
		List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
		if (comments!=null && comments.size() >0){
			for(Comment comment:comments){
				if (comment!= null){
					Map<String,Object> c = new LinkedHashMap<String,Object>();
		        	c.put("id", comment.getInt("id"));
		        	c.put("content", comment.getStr("content"));
		        	c.put("url", comment.getStr("url"));
		        	c.put("type", comment.getStr("type"));
		        	c.put("length", comment.getInt("length"));
		        	c.put("updatetime", DateUtil.meetDateTimeFormat.format(new Date(comment.getTimestamp("updatetime").getTime())));
		        	c.put("zan", comment.getInt("zan"));
		        	c.put("iszan", CommentZan.dao.find("select * from app_zan  where commentid =" +comment.getInt("id") +"  and userid="+getPara("userid")).size()>0);
		        	c.put("sub", comment.getInt("sub"));
		        	c.put("userid", comment.getInt("userid"));
		        	c.put("head", comment.getStr("head"));
		        	c.put("nickname", comment.getStr("nickname"));
		        	record.add(c);
				}
	        }
		}
        result.put("record", record);
		result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 评论下的子评论
	 */
	public void subcomments(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		
		int currentPage = 1;
        int maxCount = 20;
        try{
            currentPage = getParaToInt("currentPageStr");
            maxCount = getParaToInt("maxCountStr");
        } catch (Exception e){
        }
        int offset = (currentPage -1) * maxCount;
        
		List<SubComment> subcomments = SubComment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type,  b.nickname,b.head,a.length  from app_subcomment as a  left join sdw_member as b on a.userid = b.userid  where a.commentid =" +getPara("id")+ " order by a.inputtime desc  limit "+offset+" , "+maxCount );
		
		List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
        for(SubComment subComment:subcomments){
        	Map<String,Object> c = new LinkedHashMap<String,Object>();
        	c.put("id", subComment.getInt("id"));
        	c.put("content", subComment.getStr("content"));
        	c.put("url", subComment.getStr("url"));
        	c.put("type", subComment.getStr("type"));
        	c.put("length", subComment.getInt("length"));
        	c.put("updatetime", DateUtil.meetDateTimeFormat.format(new Date(subComment.getTimestamp("updatetime").getTime())));
        	//c.put("zan", subComment.getInt("zan"));
        	//c.put("iszan", CommentZan.dao.find("select * from app_zan  where commentid =" +comment.getInt("id") +"  and userid="+getPara("userid")).size()>0);
        	//c.put("sub", subComment.getInt("sub"));
        	c.put("userid", subComment.getInt("userid"));
        	c.put("head", subComment.getStr("head"));
        	c.put("nickname", subComment.getStr("nickname"));
        	record.add(c);
        }
        result.put("record", record);
		result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 发布评论
	 */
	public void publishcomment(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Article article = Article.dao.findById(getPara("id"));
		if(article!=null){
			String type = "txt";
			if(!StringUtil.isEmpty(getPara("type")) ){
				type = getPara("type");
			}
			int length = 0;
			int userid =0 ;
			try{
				userid = getParaToInt("userid");
				length = getParaToInt("length");
			} catch (Exception e){
				
			}
			Member member = Member.dao.findFirst("select * from sdw_member where userid ="+userid);
    		if (member!=null){
    			Member member2 = Member.dao.findFirst("select a.userid, c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
				if ("游客".equalsIgnoreCase(member2.getStr("groupName"))){
					result.put("errcode", "E20009");
					result.put("errmsg", E20009);
				} else {
					Comment comment = new Comment();
	    			comment.set("content", getPara("content"));
	    			if (!StringUtil.isEmpty(getPara("url"))){
	    				comment.set("url", PicUtil.QINIU_DIR +getPara("url").replaceAll(PicUtil.QINIU_DIR , ""));
	    			}
	    			comment.set("type", type);
	    			comment.set("length", length);
	    			comment.set("userid", userid);
	    			comment.set("artid", getPara("id"));
	    			comment.set("inputtime", new Date().getTime()/1000);
	    			comment.save();
	    			if (article.getInt("type")==4){
	    				try {
		    				int now = Integer.parseInt(DateUtil.commonDateIndexFormat.format(new Date())) ;
		    				int lastUpdate = 0;
		    				if (StringUtil.isEmpty(member.getStr("staminaUpdate"))){
		    					member.set("staminaUpdate", DateUtil.commonDateIndexFormat.format(new Date()));
		    					member.set("stamina", 1);
		        				member.update();
		    				} else {
		    					lastUpdate = Integer.parseInt(member.getStr("staminaUpdate")) ;
			    				if (now>(lastUpdate+6)){
			    					member.set("staminaUpdate", DateUtil.commonDateIndexFormat.format(new Date()));
			    					member.set("stamina", member.getInt("stamina")+1);
			        				member.update();
			    				}
		    				}
		    			} catch (Exception e){
		    				
		    			}
	    			}
	    			if (article.getInt("type")==6){
	    				member.set("pk", member.getInt("pk")+1);
	    				member.update();
	    			}
	    			result.put("id", comment.getInt("id"));
	    			result.put("errcode", SUCCESS);
	    			result.put("errmsg", SUCCESS_MSG);
				}
    			
    		} else {
    			result.put("errcode", "E20001");
    			result.put("errmsg", E20001);
    		}
		}
		
		renderText(JSONArray.fromObject(result).toString());
	}
	
	/*
	 * 发布子评论
	 */
	public void publishsubcomment(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Comment comment = Comment.dao.findById(getPara("id"));
		if(comment!=null){
			String type = "txt";
			if(!StringUtil.isEmpty(getPara("type")) ){
				type = getPara("type");
			}
			int length = 0;
			int userid =0 ;
			try{
				userid = getParaToInt("userid");
				length = getParaToInt("length");
			} catch (Exception e){
				
			}
			Member member = Member.dao.findFirst("select * from sdw_member where userid ="+userid);
    		if (member!=null){
    			Member member2 = Member.dao.findFirst("select a.userid, c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
				if ("游客".equalsIgnoreCase(member2.getStr("groupName"))){
					result.put("errcode", "E20009");
					result.put("errmsg", E20009);
				} else {
					SubComment subComment = new SubComment();
	    			subComment.set("content", getPara("content"));
	    			if (!StringUtil.isEmpty(getPara("url"))){
	    				subComment.set("url", PicUtil.QINIU_DIR +getPara("url").replaceAll(PicUtil.QINIU_DIR , ""));
	    			}
	    			subComment.set("type", type);
	    			subComment.set("length", length);
	    			subComment.set("userid", userid);
	    			//subComment.set("artid", getPara("id"));
	    			subComment.set("commentid", getPara("id"));
	    			subComment.set("inputtime", new Date().getTime()/1000);
	    			subComment.save();
	    			
	    			List<SubComment> subcomments = SubComment.dao.find("select * from app_subcomment where commentid ="+getPara("id"));
	    			comment.set("sub", subcomments.size());
	    			comment.update();
	    			result.put("id", subComment.getInt("id"));
	    			result.put("errcode", SUCCESS);
	    			result.put("errmsg", SUCCESS_MSG);
				}
    		} else {
    			result.put("errcode", "E20001");
    			result.put("errmsg", E20001);
    		}
		}
		
		renderText(JSONArray.fromObject(result).toString());
	}
	
	public void zancomment(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Comment comment = Comment.dao.findById(getPara("id"));
		if(comment!=null){
			CommentZan commentZan = CommentZan.dao.findFirst("select * from app_zan where userid="+getPara("userid")+ " and commentid="+getPara("id"));
			if(commentZan!=null){
				result.put("errcode", "E20006");
				result.put("errmsg", E20006);
			} else{
				
				Member member2 = Member.dao.findFirst("select a.userid, c.`name` as groupName from  sdw_member as a  LEFT JOIN sdw_member_group as c on a.groupid = c.groupid where a.userid ="+getPara("userid"));
				if ("游客".equalsIgnoreCase(member2.getStr("groupName"))){
					result.put("errcode", "E20009");
					result.put("errmsg", E20009);
				} else {
					commentZan = new CommentZan();
					commentZan.set("userid", getPara("userid"));
					commentZan.set("commentid", getPara("id"));
					commentZan.save();
					CommentZan subCount = CommentZan.dao.findFirst("select count(id) as total from app_zan where commentid="+getPara("id"));
					comment.set("zan", subCount.get("total"));
					comment.update();
					result.put("zan", comment.get("zan"));
					result.put("errcode", SUCCESS);
					result.put("errmsg", SUCCESS_MSG);
				}
			}
			
		} 
		renderText(JSONArray.fromObject(result).toString());
	}
	
	
	// 预习复习 、每日一句  得分
	public void updateScore(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Article article = Article.dao.findById(getPara("id"));
		if (article!=null){
			
			Score score = new Score();
			int type = 0;
			try{
				type = getParaToInt("type");
			} catch(Exception e){
				
			}
			if(type ==11 || type ==15){
				score = Score.dao.findFirst("select * from app_score where artid ="+getPara("id")+" and userid="+getPara("userid"));
			}
			
			score.set("artid", getPara("id"));
			score.set("userid", getPara("userid"));
			
			if(type ==11){
				score.set("score1", getParaToInt("score"));
			} else if(type ==15){
				score.set("score2", getParaToInt("score"));
			} else {
				score.set("score", getParaToInt("score"));
			}
			score.set("success", 1);
			score.set("inputtime", new Date().getTime()/1000);
			if(score.get("id")!=null){
				score.update();
			} else{
				score.save();
			}
			
		}
		result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
		renderText(JSONArray.fromObject(result).toString());
	}
	
	
	/*
	 * 首页
	 */
	public void home(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Article wArticle = Article.dao.findFirst("select * from app_article where app_article.type = 1 ORDER BY id desc ");
		if (wArticle!=null){
			result.put("mp4", wArticle.getStr("mp4url"));
		}
		
		Article adArticle = Article.dao.findFirst("select * from app_article where app_article.type = 2 ORDER BY id desc ");
		if (adArticle!=null){
			result.put("pic1", adArticle.getStr("pic1"));
			result.put("pic2", adArticle.getStr("pic2"));
			result.put("pic3", adArticle.getStr("pic3"));
		}
		
		Module module9 = Module.dao.findFirst("select * from app_module where typeid= 9");
		if (module9!=null){
			result.put("title9", module9.getStr("title"));
			result.put("icon9", module9.getStr("icon"));
		}
		
		Module module10 = Module.dao.findFirst("select * from app_module where typeid= 10");
		if (module10 !=null){
			result.put("title10", module10.getStr("title"));
			result.put("icon10", module10.getStr("icon"));
		}
		List<Member> memberPK = Member.dao.find("select * from sdw_member order by pk desc  limit 0, 5 ");
		List<Map<String,Object>> record1 = new LinkedList<Map<String,Object>>();
		for(Member member:memberPK){
			Map<String,Object> c = new LinkedHashMap<String,Object>();
			c.put("nickname", member.getStr("nickname"));
			c.put("head", member.getStr("head"));
			c.put("pk", member.getInt("pk"));
			record1.add(c);
		}
		result.put("record1", record1);
		
		List<Member> memberN = Member.dao.find("select * from sdw_member order by stamina desc  limit 0, 5 ");
		List<Map<String,Object>> record2 = new LinkedList<Map<String,Object>>();
		for(Member member:memberN){
			Map<String,Object> c = new LinkedHashMap<String,Object>();
			c.put("nickname", member.getStr("nickname"));
			c.put("head", member.getStr("head"));
			c.put("stamina", member.getInt("stamina"));
			record2.add(c);
		}
		result.put("record2", record2);
		result.put("errcode", SUCCESS);
		result.put("errmsg", SUCCESS_MSG);
		renderText(JSONArray.fromObject(result).toString());
	}
	
	public void report(){
        Map<String,Object> result = new LinkedHashMap<String,Object>();
        result.put("errcode", SUCCESS);
        result.put("errmsg", SUCCESS_MSG);
        renderText(JSONArray.fromObject(result).toString());
    }
	
	public void start(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		
		Article adArticle = Article.dao.findFirst("select * from app_article where app_article.type = -1 ORDER BY id desc ");
		if (adArticle!=null){
			result.put("pic", adArticle.getStr("pic1"));
		}
        result.put("errcode", SUCCESS);
        result.put("errmsg", SUCCESS_MSG);
        renderText(JSONArray.fromObject(result).toString());
	}

	/*
	 * 我的学习
	 */
	public void study(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Article adArticle = Article.dao.findFirst("select * from app_article where app_article.type = 12 ORDER BY id desc ");
		if (adArticle!=null){
			result.put("pic1", adArticle.getStr("pic1"));
			result.put("pic2", adArticle.getStr("pic2"));
			result.put("pic3", adArticle.getStr("pic3"));
		}
		Module module13 = Module.dao.findFirst("select * from app_module where typeid= 13");
		if (module13!=null){
			result.put("title4", "预约课文");
			result.put("pic4", module13.getStr("icon"));
			result.put("subpic4", module13.getStr("subicon"));
			
			result.put("content4", module13.getStr("title"));
		}
		Module module11 = Module.dao.findFirst("select * from app_module where typeid= 11");
		if (module11!=null){
			result.put("title5", module11.getStr("title"));
			result.put("pic5", module11.getStr("icon"));
		}
		Module module14 = Module.dao.findFirst("select * from app_module where typeid= 14");
		if (module14!=null){
			result.put("title6", module14.getStr("title"));
			result.put("pic6", module14.getStr("icon"));
		}
		Module module15 = Module.dao.findFirst("select * from app_module where typeid= 15");
		if (module15!=null){
			result.put("duration", module15.get("value"));
			result.put("title7", module15.getStr("title"));
			result.put("pic7", module15.getStr("icon"));
		}
        result.put("errcode", SUCCESS);
        result.put("errmsg", SUCCESS_MSG);
        renderText(JSONArray.fromObject(result).toString());
	}
	
	
	/*
	 * 评价课程
	 */
	public void courseTask(){
		Map<String,Object> result = new LinkedHashMap<String,Object>();
		Order order = Order.dao.findFirst("select * from sdw_destine where catidid ="+ getPara("id") +" and userid="+getPara("userid"));
		if(order != null) {
			try{
				System.out.println(order.get("score"));
			if ( order.get("score") != null  && order.getInt("score") >0){
				result.put("errcode", "E20026");
				result.put("errmsg", E20026);
			} else {
				int total = 0;
				Course course = Course.dao.findById(getPara("id"));
				boolean taskflg = course.getInt("catid") == 87;
				if (!taskflg){
					List<Article> taskList = Article.dao.find("select id from app_article where type=16 and parentid  = "+course.get("prepareid") );
					if (taskList!=null){
						total = taskList.size();
					}	
					List<Score> taskOrderList = Score.dao.find("select * from app_score where  userid ="+getPara("userid") +" and  artid in (select id from app_article where parentid  = "+ course.get("prepareid")+") and score1 > 89");
					if (taskOrderList!=null){
						taskflg = (taskOrderList.size() >= total);
					}
				}
				if (taskflg){
					// 1 满意, 2一般, 3不满意
					order.set("feedback", getPara("feedback"));
					order.set("feedback_keyword", getPara("content"));
					order.set("score", getPara("score"));
					order.update();
					result.put("errcode", SUCCESS);
			        result.put("errmsg", SUCCESS_MSG);
				}else {
					result.put("errcode", "E20025");
					result.put("errmsg", E20025);
				}
				
			}
			} catch (Exception e){
				e.printStackTrace();
				System.out.println(e.getMessage());
			}
			
		}
		
        renderText(JSONArray.fromObject(result).toString());
	}

	public void share(){
		try {
			Article article = Article.dao.findFirst("select *, FROM_UNIXTIME(inputtime) as updatetime from app_article where id = "+getPara("id"));
			if (article==null){
				renderText("页面不存在");
			} else {
	    		setAttr("logo", article.get("logo"));
				setAttr("title", article.get("title"));
				setAttr("mp3", article.get("mp3url"));
				setAttr("content", article.get("content"));
				setAttr("updatetime", DateUtil.meetDateTimeFormat.format(new Date(article.getTimestamp("updatetime").getTime())));
				List<Comment> comments = Comment.dao.find("select a.id , a.userid , a.content ,a.url , FROM_UNIXTIME(a.inputtime)  as updatetime,a.type, a.zan, b.nickname,b.head,a.length,a.sub as sub   from app_comment as a  left join sdw_member as b on a.userid = b.userid  where a.artid =" +getPara("id")+ " order by a.inputtime desc  limit 0 ,20 ");
				Comment commentCount = Comment.dao.findFirst("select count(1)  as count from app_comment  where artid="+getPara("id"));
				setAttr("count", commentCount.get("count"));
				
				List<Map<String,Object>> record = new LinkedList<Map<String,Object>>();
		        for(Comment comment:comments){
		        	Map<String,Object> c = new LinkedHashMap<String,Object>();
		        	c.put("id", comment.getInt("id"));
		        	c.put("content", comment.getStr("content"));
		        	c.put("url", comment.getStr("url"));
		        	c.put("type", comment.getStr("type"));
		        	c.put("length", comment.getInt("length"));
		        	c.put("updatetime", DateUtil.meetDateTimeFormat.format(new Date(comment.getTimestamp("updatetime").getTime())));
		        	c.put("zan", comment.getInt("zan"));
		        	c.put("sub", comment.getInt("sub"));
		        	c.put("userid", comment.getInt("userid"));
		        	c.put("head", comment.getStr("head"));
		        	c.put("nickname", comment.getStr("nickname"));
		        	record.add(c);
		        }
		        setAttr("comments", record);
				render("share.html");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}


